<?php

/*
 * Main controller class - communicate with restful services
 */

class Main extends CI_Controller {

    private $data;

    function __construct() {
        parent::__construct();

        // Load the rest client spark
        $this->load->spark('restclient/2.1.0');

        $this->rest->initialize(array(
            'server' => REST_URL_HOTELS,
            'http_user' => 'online',
            'http_pass' => 'booking',
            'http_auth' => 'basic' // or 'digest'
        ));

        $this->activeLang = $this->lang->mci_current();

        require_once EXTERNAL_URL . 'urlify.php';

        $this->load->driver('cache', array('adapter' => 'file')); // enable caching driver
        // Destinations and home data
        $home_page = array('recommended', 'specialHotels', 'specialDests', 'popular', 'visited', 'googlemap', 'allDests');

        $file = cache_filename(array('lang' => $this->activeLang), 'combined');

        if (!$combined = $this->cache->get($file)) {

            $combined = $this->rest->post(
                    'home', array('lang' => $this->activeLang, 'input' => $home_page));

            if (DO_CACHE)
                $this->cache->save($file, $combined, 300);
        }

        $this->firephp->log($combined);

        foreach ($home_page as $key) // copy results to $this->data
            $this->data[$key] = $combined->{$key};
    }

    public function index() {
        $this->home();
    }

    /*
     * Home page
     *
     * @params :
     *      input ('popular', 'visited', 'specialHotels', 'specialDests', 'recommended', 'googlemap','recentlybooked', 'allDests')
     */

    public function home() {

        if (isset($this->data['googlemap'])) // parse array of objects with coordinates
            $this->data['googlemap'] = make_google_map($this->data['googlemap']);

        $this->data = currency_convert($this->data); // Convert currency

        $this->data['seo_title'] = lang('title-home');
        $this->data['seo_description'] = lang('description-home');

//        $this->firephp->log($this->data);

        $this->template->load('site/home', $this->data);
    }

    /*
     * Search page
     *
     * @params:
     *      check_in
     *      check_out
     *      nr_adults
     *      ages
     *      dest_hot
     *
     */

    public function search() {

        if (isset($_GET['preview']))
            $rest_method = 'searchPreview';
        else
            $rest_method = 'search';

        $file = cache_filename($_GET, 'results');
        if (!$this->data['results'] = $this->cache->get($file)) {

            $this->data['results'] = $this->rest->post($rest_method, $_GET);

            if (DO_CACHE)
                $this->cache->save($file, $this->data['results'], 300);
        }
        if (isset($_GET['acc_type']))
            filter_acc_type($this->data['results'], $_GET['acc_type']);

        loadJoinedGroupsAttributes($this->data['results']);

        $items = $rest_method == 'search' ? make_sort_price_available($this->data['results']) : $this->data['results'];
        $this->data['items'] = json_encode($items);

        $this->data['unique'] = findUniqueMakeCount($this->data['results']); // find unique filter attributes
        $this->data['unique_prices'] = findUniquePricesMakeCount($this->data['results'], isset($_GET['preview'])); // find unique prices for filter
        $this->data['unique_stars'] = findUniqueStarsMakeCount($this->data['results']); // find unique stars for filter
        // sort, splice and shuffle facilities & services
        sort_attributes($this->data['unique']);
        if (count($this->data['unique']) > 23)
            array_splice($this->data['unique'], 23);

        shuffle($this->data['unique']);

        // sort stars array
        ksort($this->data['unique_stars']);

        // load objects for maps
        $this->data['googlemap'] = make_google_map($this->data['results']);

        $this->data = currency_convert($this->data); // Convert currency

        $this->data['seo_title'] = search_title();
        $this->data['seo_description'] = search_description();
        $this->data['h1_title'] = search_h1();

//        $this->firephp->log($this->data);

        $this->template->load('site/results', $this->data);
    }

    private function _findRoom(&$details) {

        if (isset($details->rooms))
            foreach ($details->rooms as $index => $room) :
                if ($room->room_ID == $_GET['room_id']):
                    $details->cur_room = $room;
                    break;
                endif;
            endforeach;
    }

    /*
     * Autocomplete
     *
     * @params :
     *      name_startsWith
     *      plus_hotels
     *
     */

    public function destinations_hotels_JSON($plus_hotels = FALSE) {

        $rest_data = array(
            "name_startsWith" => $_GET['name_startsWith'],
            "plus_hotels" => $plus_hotels,
            "lang" => $this->activeLang
        );

        $file = cache_filename($rest_data, 'combined');

        if (!$items = $this->cache->get($file)) {

            $items = $this->rest->post("destinationsHotelsAutocomplete", $rest_data);

            if (DO_CACHE)
                $this->cache->save($file, $items, 300);
        }

        // parse each row to regular array
        if ($plus_hotels):
            $myItems = array();
            foreach ($items as $value)
                $myItems[] = get_object_vars($value); // convert STD to Array

            $cnt = count($myItems);  //trip whitespace
            for ($index = 0; $index < $cnt; $index++) :
                $myItems[$index]['name'] = trim($myItems[$index]['name']);
                $myItems[$index]['label'] = trim($myItems[$index]['label']);

            endfor;

            // sort
            sort_array_of_array($myItems, 'name', TRUE);
            $items = $myItems;
        endif;

        //echo JSON to page
        $response = $_GET["callback"] . "(" . json_encode(array('items' => $items)) . ")";
        echo $response;
    }

    /*
     * Object details with rooms and prices
     *
     * @params:
     *      check_in
     *      check_out
     *      nr_adults
     *      ages
     *      hotel_id
     *
     */

    public function accommodation($i) {

        if (isset($_GET['preview']))
            $rest_method = 'detailsPreview';
        else
            $rest_method = 'details';

        $id = explode('-', $i);
        $ide = $id[count($id) - 1];

        $_GET['hotel_id'] = $ide;

        $this->data['details'] = $this->rest->post($rest_method, $_GET);

        $this->_findRoom($this->data['details']); // Load current room
        // Make distances from available
        $this->data['distances_from'] = array();

        $dFromKey = array('Distances from', 'Udaljenosti objekta od', 'Расстояния от', 'Afstanden van');

        if (isset($this->data['details']->facilities))
            foreach ($this->data['details']->facilities as $key => $value) :
                if (in_array($key, $dFromKey)):

                    $this->data['distances_from'] = $this->data['details']->facilities->{$key};
                    unset($this->data['details']->facilities->{$key});
                endif;

            endforeach;

        // load objects for maps
        $this->data['googlemap'] = make_google_map(array($this->data['details']));

        $this->data['seo_title'] = $this->data['details']->seo_title != "" ? $this->data['details']->seo_title : $this->data['details']->object_name . ' | Globtourmontenegro';
        $this->data['seo_description'] = $this->data['details']->seo_description;

        $this->template->load('site/accommodation', $this->data);
    }

    public function prices() {

        $this->data['details'] = $this->rest->post('detailsWithAvailbleInfo', $_GET);

        if (isset($this->data['details']->accommNotAvailbale)):

            $error = $this->data['details'];

            switch ($error->message):

                case $error->message == 'not_available' || $error->message == 'too_meny_person':
                    $msg = lang($error->message);
                    break;

                case 'min_stay':
                    $msg = lang($error->message) . $error->value . ' ' . lang('days') . '!';
                    break;

                case 'min_ps':
                    $msg = lang($error->message) . $error->value . ' ' . lang('person') . '!';
                    break;

            endswitch;

            $response = array(
                'total' => 0,
                'available' => FALSE,
                'message' => $msg,
                'value' => $this->data['details']->value,
            );

        else:

            $this->_findRoom($this->data['details'][0]); // Load current room

            foreach ($this->data['details'][0]->rooms as $index => $room) :

                if ($room->room_ID == $_GET['room_id']):

                    $response = array(
                        'total' => $room->selling_total,
                        'available' => TRUE,
                        'message' => '',
                        'value' => ''
                    );

                    break;
                endif;


            endforeach;

        endif;

        if (!isset($response))
            $response = array(
                'total' => 0,
                'available' => FALSE,
                'message' => lang('not_available'),
                'value' => '',
            );

        echo json_encode($response);
    }

    /*
     * Customer Form Show Object and room with prices
     *
     * @params:
     *      check_in
     *      check_out
     *      nr_adults
     *      nr_childrens
     *      nr_babies
     *      hotel_id
     *      room_id
     *
     */

    public function checkout() {
        
        return;

        $this->data['reservation'] = $this->rest->post("customerForm", $_GET);

        $this->load->config('countries');

        $this->load->helper('percent');
        $this->template->set_view('template_checkout');

        $cookie = array(
            'name' => 'globtour_cookie',
            'value' => '1',
            'expire' => '86500'
        );

        $this->input->set_cookie($cookie); // Set coockie for redirecting on confirmation page reload
//            $this->firephp->log($this->data['reservation']);

        $this->data['seo_title'] = lang('title-reservation_details');
        $this->data['seo_description'] = "";

        $this->template->load('site/checkout', $this->data);
    }

    /*
     * Create reservation write reservation to DB
     *
     * method: createReservation
     *
     * @params:
     *      check_in
     *      check_out
     *      nr_adults
     *      ages
     *      hotel_id
     *      room_id
     *      selling_type_ID
     *      payment_method
     *      payment_options
     *      note || remarks
     *      sex
     *      email
     *      name || firstname
     *      surname || lastname
     *      phone
     *      address
     *      city
     *      country
     *      zip
     *
     */

    public function confirmation() {
        
        return;

        $coockie = get_cookie('globtour_cookie'); // Redirect if page reload

        if (!$coockie)
            redirect(lang_url());

        $rest_data = $_GET;
        $rest_data['agency'] = 'globtour';

//            $this->firephp->log($rest_data);

        $this->data['reservation'] = $this->rest->post("createReservation", $rest_data);

        delete_cookie('globtour_cookie');

        $this->data['seo_title'] = lang('title-confirmation');
        $this->data['seo_description'] = "";

        $this->template->set_view('template_checkout');
        $this->template->load('site/checkout_thanks', $this->data);
    }

    /*
     * Question
     */

    public function question() {

        $rest_data = $_GET;
        $rest_data['agency'] = 'globtour';
        $answer = $this->rest->post("gotQuestion", $rest_data);

        echo json_encode($answer);
    }

    /*
     * Subscribe
     */

    public function subscribe() {

        $answer = $this->rest->post("subscribe", $_GET);

        echo json_encode($answer);
    }

    /*
     * Show Reservation Cancellation
     */

    public function show_cancellation() {
        
        return;

        $this->template->set_view('template_checkout');
        $data['seo_title'] = "Reservation cancellation";
        $data['seo_description'] = "";
        $this->template->load('parts/cancel', $data);
    }

    /*
     * Show Reservation Cancellation Thanx
     */

    public function show_cancellation_tnx() {
        
        return;

        //cancelReservation
        $answer = $this->rest->post("cancelReservation", $_GET);

        $this->template->set_view('template_checkout');
        $data['seo_title'] = "Reservation cancellation";
        $data['seo_description'] = "";
        $this->template->load('parts/thanks', $data);
    }

    /*
     * Show Review Form
     */

    public function show_review_form() {
        
        return;

        //reservation info
        $rest_data = array(
            'reservation_id' => $_GET['reservation_ID']
        );
        $data['reservation'] = $this->rest->post("showReservationInfo", $rest_data);

        $this->template->set_view('template_checkout');
        $data['seo_title'] = "User review";
        $data['seo_description'] = "";

        //            $this->firephp->log($data);
        $this->template->load('parts/review_form', $data);
    }

    /*
     * Submit Review Form
     */

    public function subit_review_form() {
        
        return;

        //cancelReservation
        $this->rest->post("submitReview", $_GET);

        $this->template->set_view('template_checkout');
        $data['seo_title'] = "User review";
        $data['seo_description'] = "";
        $this->template->load('parts/thanks', $data);
    }

}
